package com.project.petLossSystem.controller.admin;

import com.project.petLossSystem.common.Constants;
import com.project.petLossSystem.common.ServiceResultEnum;
import com.project.petLossSystem.po.IndexCarousel;
import com.project.petLossSystem.service.IndexCarouselService;
import com.project.petLossSystem.util.PageQueryUtil;
import com.project.petLossSystem.util.Result;
import com.project.petLossSystem.util.ResultGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;

@Controller
@RequestMapping("/admin")
public class IndexCarouselController {
    @Autowired
    private IndexCarouselService indexCarouselService;

    @GetMapping("/indexCarousels")
    public String indexCarousel() {
        return "/pc/admin/index_carousels";
    }

    @PostMapping("/indexCarousels/save")
    @ResponseBody
    public Result save(@RequestParam("uploadFile") MultipartFile file, @RequestParam("redirectUrl") String redirectUrl) {
        if (!StringUtils.hasText(redirectUrl)) {
            return ResultGenerator.failureResult("跳转链接不能为空！");
        }
        String carouselUrl;
        File imageFile = null;
        try {
            // 判断是否是图片类型
            if (ImageIO.read(file.getInputStream()) == null) {
                return ResultGenerator.failureResult("请上传图片类型文件！");
            }
            // 获取文件后缀名
            String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            // 文件通用日期格式名
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.DATE_FORMAT_FILE_NAME);
            StringBuilder newFileName = new StringBuilder();
            newFileName.append(simpleDateFormat.format(new Date()))
                    .append("_")
                    .append(new Random().nextInt(100))
                    .append(suffixName);
            // 创建文件
            imageFile = new File(Constants.File_IMAGE_UPLOAD_DIC + Constants.CAROUSEL_URL + newFileName.toString());
            // 复制并输出内容到新文件
            file.transferTo(imageFile);
            // 返回图片的url
            carouselUrl = Constants.CAROUSEL_URL + newFileName.toString();
        } catch (Exception e) {
            e.printStackTrace();
            imageFile.delete();
            return ResultGenerator.failureResult("上传文件失败！");
        }
        if (indexCarouselService.insertCarouse(carouselUrl, redirectUrl)) {
            return ResultGenerator.successResult();
        } else {
            // 插入失败，需要删除图片
            if(imageFile != null){
                imageFile.delete();
            }
            return ResultGenerator.failureResult("上传文件失败！");
        }
    }

    @GetMapping("/indexCarousels/list")
    @ResponseBody
    public Result list(@RequestParam Map<String, Object> params) {
        if (ObjectUtils.isEmpty(params.get("page")) || ObjectUtils.isEmpty(params.get("rows"))) {
            return ResultGenerator.failureResult("参数异常！");
        }
        PageQueryUtil pageQueryUtil = new PageQueryUtil(params);
        return ResultGenerator.successResult(indexCarouselService.getCarouselPage(pageQueryUtil));
    }

    @PutMapping("/indexCarousels/update")
    @ResponseBody
    public Result update(@RequestBody IndexCarousel carousel) {
        if (ObjectUtils.isEmpty(carousel.getCarouselId()) || !StringUtils.hasText(carousel.getCarouselUrl()) || !StringUtils.hasText(carousel.getRedirectUrl())) {
            return ResultGenerator.failureResult("参数异常！");
        }
        String result = indexCarouselService.updateCarousel(carousel);
        if (result.equals(ServiceResultEnum.SUCCESS.getResult())) {
            return ResultGenerator.successResult();
        } else return ResultGenerator.failureResult(result);
    }

    @PutMapping ("/indexCarousels/delete")
    @ResponseBody
    public Result delete(@RequestBody Integer[] ids) {
        if (ids.length < 1) {
            return ResultGenerator.failureResult("参数异常！");
        }
        if (indexCarouselService.deleteCarousels(ids)) {
            return ResultGenerator.successResult();
        } else return ResultGenerator.failureResult("删除失败!");
    }
}
